<?php
namespace app\manage\controller;
use app\common\model\User as UserModel;
use app\common\model\China;
use app\common\model\Relation;
use think\Validate;
/**
 * 用户管理
 * @author zlj <389843954@qq.com>
 */
class User extends Common
{
    public $user;

    public function _initialize()
    {
        $this->user = model('User');
    }

    /**
     * 用户列表
     */
    public function index()
    {
        $keyword = input('get.keyword','');
        $ban = input('get.ban', 0);
        $userModel = new UserModel();
        $order = ['t1'=>'desc'];
        $pageSize = isset($pageSize)?$pageSize:15;
        
        $where = $pageParam = array();

        if ($keyword) {
            $where['name'] = array('like','%'.$keyword.'%');
            $pageParam['query']['keyword'] = $keyword;
        }
        
        $where['ban'] = array('eq', $ban);
        $pageParam['query']['ban'] = $ban;


        $data = $userModel->getAll($where,$order,$pageSize,$pageParam);
        $res = [
            'data'=>$data,
            'keyword'=>$keyword,
            'ban'=>$ban,
            'title'=>'用户列表'
        ];

        return view('', $res);
    }

    /**
     *用户添加
     */
    public function add(){

        if (request()->isPost()){
            
            $data=input('post.');
            $uid = $this->user->insertGetId(['t1' => time()]);

            $userModel = new UserModel();
            $res = $userModel->userCheck($data,$uid);

            if ($res['state']){

                $result = $userModel->allowField(true)->save($res['msg'],['uid'=>$uid]);
                if($result){
                    $type = explode(",",$data['type']);
                    $place = config('PLACE');
                    $relation = new Relation();
                    foreach ($type as $value) {

                        $rarr['uid'] = $uid;
                        $rarr['rid'] = $value;
                        $rarr['ctime'] = time();
                        if($value==$place['PLACE_RMAN_OPEN']['id'] || $value==$place['PLACE_RMAN_AYS']['id']){
                            //资源人
                            $rarr['referral'] = $tuid;
                            $rarr['tel'] = $tel;
                        }

                        $relation->insert($rarr);
                        unset($rarr);
                    }

                    $this->success('提交成功',url('User/index'));
                }else{
                    $this->error('提交失败,请重试!');
                }
            }else{
                $this->error($res['msg']);
            }
        }
        return view('',['title'=>'用户添加']);
    }

    /**
     *设置用户状态
     */
    public function setStatus() {

        $userModel = new UserModel();
        if (request()->isAjax()) {
            $id = input('post.id');
            $where=[
                'id'=>$id
            ];
            $data = ['valid'=>input('post.status')];

            if (!$id) {
                show(0, 'ID不存在');
            }
            $res = $userModel->updateFieldsById($where, $data);
            if ($res) {
                show(1, '操作成功');
            } else {
                show(0, '操作失败');
            }
        }
    }

    /**
     *编辑用户
     */
    public function edit(){
        $userModel = new UserModel();
        $id=input('id');
        $where['id']= $id;

        if(request()->isAjax()) {
            $data=input('post.');
            $res = $userModel->updateFieldsById($where, $data);
            if ($res!==false) {
                show(1, '操作成功');
            } else {
                show(0, '操作失败');
            }
        }else{

            $field = "*";
            $data = $userModel->getOne($field,$where);
            $success_url = request()->server('HTTP_REFERER');
            $chinaModel = new China();
            $areas = array(
                'plist'=>$chinaModel->getList(0),
                'clist'=>$data['pid']?$chinaModel->getList($data['pid']):array(),
                'alist'=>$data['cid']?$chinaModel->getList($data['cid']):array(),
            );
            $res = [
                'data'=>$data,
                'success_url'=>$success_url,
                'areas'=>$areas,
                'title'=>'用户编辑'
            ];
            return view('',$res);
        }
    }


    /**
     * 省市区列表
     * @return [type] [description]
     */
    public function areas(){
        if(request()->isAjax()){
            $chinaModel = new China();
            $pid = input('post.pid',0);
            $areasList = $chinaModel->getList($pid);

            show(1,'',$areasList);
        }
    }

    /**
     * 通过审核
     */
    public function checkPass(){
        $model=new UserModel();
        try {
            if (request()->isAjax()) {
                $id = input('post.id');
                $valid = input('post.valid');

                $status = ['valid'=>$valid];
                $where = ['id'=>$id];
                $res = $model->updateFieldsById($where, $status);
                if ($res) {
                    show(1, '审核通过');
                } else {
                    show(0, '审核失败');
                }
            }
            show(0, '没有提交的内容');
        }catch(\Exception $e) {
            show(0, $e->getMessage());
        }
    }

    /**
     * 禁止登陆
     * @return [type] [description]
     */
    public function isban(){
        if(request()->isAjax()){

            $ban = input('ban');
            $uid = input('uid');

            if ($this->user->updateFieldsById(['uid'=>$uid],['ban'=>$ban])) {
                show(1, '操作成功');
            } else {
                show(0, '操作失败');
            }
            
        }
    }


    public function info($uid)
    {
        $model = model('Relation');

        $info = $this->user->info($uid);
        $user_info = $this->deal_user_info($info);

        $data = [
            'role' => $model->identity($uid, true, 1),
            'info' => $user_info
        ];

        return view('', [
            'title' => '审核',
            'data' => $data
        ]);
    }


    /**
     * 获取用户信息
     * @param  integer $id 用户id
     * @return array
     */
    public function profile($id)
    {	
        $data = $this->user->info($id);

        $model = model('Relation');
        $role = $model->identity($id, false, 1);


        $data['role'] = $role;
        return $data;
    }


    /**
     * 认证申请列表
     * @return [type] [description]
     */
    public function apply()
    {
        $keyword = input('keyword', '');
        $mstate = input('mstate', 0);
        $pageParam = [];
        $map = [];

        if ($keyword) {
            $pageParam['query']['keyword'] = $keyword;
            $map = [
                'name' => ['like', '%' . $keyword . '%']
            ];
        }
        $model = model('Relation');
        $data = $model->getList($map, $pageParam);
        return view('', [
            'title' => '认证申请列表',
            'keyword' => $keyword,
            'data'  => $data
        ]);
    }


    /**
     * 认证审核
     * @param  integer $uid 用户id
     * @return html
     */
    public function review($uid)
    {
        if (request()->isAjax()) {

            $data = [
                'uid' => input('post.uid'),
                'rid' => input('post.id'),
                'auth' => input('post.auth'),
                'opinion' => input('post.opinion'),
                'auditor' => 1,
                'auditime' => time()
            ];

            $result = $this->validate($data, 'Relation.conventional');
            if (true !== $result) {
                show(0, $result);
            }

            $model = model('Relation');

            if ($model->audit($data)) {
                show(1, '审核完成');
            } else {
                show(0, '审核失败');
            }
            
        }

        $model = model('Relation');

        $info = $this->user->info($uid);
        $user_info = $this->deal_user_info($info);

        $data = [
            'role' => $model->identity($uid),
            'info' => $user_info
        ];

        return view('', [
            'title' => '审核',
            'data' => json_encode($data)
        ]);
    }

    /**
     * 处理审核展示数据
     * @param  array $data 用户数据
     * @return array
     */
    private function deal_user_info($data)
    {
        $img = ['id_just', 'id_back', 'contract_1', 'contract_2', 'contract_3', 'cert_d', 'cert_z', 'cert_l', 'cert_2', 'cert_3', 'cert_4', 'license_1', 'license_2'];

        $note = json_decode($data['note'], true);

        $data['photo'] = $data['photo'] ? '/uploads/' . $data['photo'] : '';

        if ($note) {
            $keys = array_keys($note);
            foreach ($keys as $key) {
                if (in_array($key, $img)) {
                    $note[$key] = '/uploads/' . $note[$key];
                }
            }

            $data['note'] = $note;
        }


        // 省市县
        $china = model('China');
        $pid = $china->areas($data['pid']);
        $data['pid'] = $pid['name'];
        $cid = $china->areas($data['cid']);
        $data['cid'] = $cid['name'];
        $aid = $china->areas($data['aid']);
        $data['aid'] = $aid['name'];

        return $data;
    }


    // 资源人审核
    public function review_resource_man()
    {
        if (request()->isAjax()) {
            $data = input('post.');

            if (model('Relation')->audit_resource_man($data['auth'], $data['uid'], $data['rid'], $data['tel'], $data['ctime'])) {
                show(1, '审核成功');
            } else {
                show(0, '审核失败');
            }
            
        }
    }


    public function demo()
    {
        $data = $this->profile(5);
        dump($data);
    }



}
